package wwl.lsf.learn.javassit;

import javassist.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Title
 * @Author wangwenliang
 * @Date 2020/5/29
 * @Description
 */
public class UpdatePersonClass {
    public static void main(String[] args) throws Exception {
        newMethod();
    }

    public static void updateMethod() throws Exception {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.get("wwl.lsf.learn.javassit.Person");
        CtMethod flyCtMethod = ctClass.getDeclaredMethod("fly");
        flyCtMethod.insertBefore("System.out.println(\"起飞之前准备降落伞\");");
        flyCtMethod.insertAfter("System.out.println(\"成功落地\");");

        Object person = ctClass.toClass().newInstance();

        Method fly = person.getClass().getMethod("fly");
        fly.invoke(person);
    }

    public static void newMethod() throws Exception {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.get("wwl.lsf.learn.javassit.Person");
        CtMethod joinMethod = new CtMethod(CtClass.voidType, "joinMethod", new CtClass[]{}, ctClass);
        joinMethod.setModifiers(Modifier.PUBLIC);
        joinMethod.setBody("System.out.println(\"我是直接新增的方法\");");
        ctClass.addMethod(joinMethod);
        Object person = ctClass.toClass().newInstance();

        Method fly = person.getClass().getMethod("joinMethod");
        fly.invoke(person);

    }
}
